import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GUI } from "three/addons/libs/lil-gui.module.min.js";
import { mesh, meshGroup } from "./mesh.js";

const scene = new THREE.Scene();
scene.add(meshGroup);

const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(500, 500, 500);
scene.add(directionalLight);
const ambientLight = new THREE.AmbientLight(0x404040, 1);
scene.add(ambientLight);

// 创建相机
const camera = new THREE.PerspectiveCamera(
	60,
	window.innerWidth / window.innerHeight,
	0.1,
	10000 // 相机的范围
);
camera.position.set(600, 600, 600);
camera.lookAt(0, 0, 0);

// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

renderer.domElement.addEventListener(
	"click",
	(event) => {
		const x = (event.clientX / window.innerWidth) * 2 - 1;
		const y = -(event.clientY / window.innerHeight) * 2 + 1;
		// console.log(x, y);

		const mouse = new THREE.Vector2(x, y);
		const raycaster = new THREE.Raycaster();
		raycaster.setFromCamera(mouse, camera);
		const intersects = raycaster.intersectObjects(scene.children);

		const arrowHelper = new THREE.ArrowHelper(
			raycaster.ray.direction,
			raycaster.ray.origin,
			3000,
			0xff0000
		);
		scene.add(arrowHelper);

		intersects.forEach((item) => {
			if (item.object.material) {
				item.object.material.color = new THREE.Color("pink");
			}
			console.log(item);
		});
	},
	false
);

// 渲染
function render() {
	requestAnimationFrame(render);
	renderer.render(scene, camera);
}
render();

//添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(1000);
scene.add(axesHelper);

//轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.addEventListener("change", function () {
	renderer.render(scene, camera);
});

//调试工具
const gui = new GUI();
